package cn.edu.javaweb.userServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.javaweb.utils.DBUtil;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	DBUtil db;
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name=request.getParameter("username");
		String pass=request.getParameter("password");
		String place=request.getParameter("place");
		System.out.println(name);
		PrintWriter out=response.getWriter();
		try{
			db=new DBUtil(); //建创对象 搭桥配置初始化
			String sql="select * from user where username='"+name+"' and password='"+pass+"' and ident='"+place+"'";
			System.out.println(sql);
			

			Map map=db.getMap(sql);
			System.out.println(map);
			String id=(String) map.get("id");
			String roster=(String) map.get("roster");
			
//			String username=(String) map.get("name");
//		    String password=(String) map.get("password");
//		    String ident=(String) map.get("ident");
//		    String sex=(String) map.get("sex");
//		    String uclass=(String) map.get("uclass");
//		    String id=(String) map.get("id");
//		    String telephone=(String) map.get("telephone");
//			request.setCharacterEncoding("utf-8");//解决乱码 
			
			HttpSession session = request.getSession(true);
			session.setAttribute("Person", map);
			session.setAttribute("id", id);
			
			if(("1").equals(roster)){
				if(("0").equals(place)){
					out.println("<script>alert('登录成功，即将跳转到用户端！！！');window.location.href='HomeServlet'</script>;");
				}else if(("1").equals(place)){
					out.println("<script>alert('登录成功，即将跳转到管理端！！！');window.location.href='volunteer/admin/home.jsp'</script>;");
				}else if(("2").equals(place)){
					out.println("<script>alert('登录成功，即将跳转到超级管理端！！！');window.location.href='SelectCollageAdmin'</script>;");
				}
			}else{
				out.println("<script>alert('该账号已加入黑名单！');window.location.href='volunteer/Login&Register.jsp'</script>;");
			}
		}catch(Exception e){
			e.printStackTrace();
			out.println("<script>alert('用户名或密码存在错误,请重新登录！！！');window.location.href='volunteer/Login&Register.jsp'</script>;");
		}
		
		
	}

	@Override
	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
